package Thread;

import java.util.Map;
import java.util.concurrent.*;

/**
 * @author VX5
 * @Title: MJC
 * @ProjectName DataStructure
 * @Description: TODO
 * @date ${DAT}16:39
 */
public class BankWaterService implements Runnable {
    //设置4个屏障，处理完后执行当前类的run方法
    private CyclicBarrier c = new CyclicBarrier(4,this);

    //假设只有4个sheet，所以只启动4个线程
    private Executor executor = Executors.newFixedThreadPool(4);

    //保存每个sheet计算出的结果
    private ConcurrentHashMap<String,Integer> sheetBankWaterCount = new ConcurrentHashMap<>();

    private void count(){
        for (int i = 0 ; i < 4; i++){
            executor.execute(() -> {
                sheetBankWaterCount.put(Thread.currentThread().getName(),1);
                //计算完成插入一个屏障
                try {
                    c.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    @Override
    public void run() {
        int result = 0;
        //汇总每个sheet计算出的结果
        for (Map.Entry<String, Integer> stringIntegerEntry : sheetBankWaterCount.entrySet()) {
            result += stringIntegerEntry.getValue();
        }
        sheetBankWaterCount.put("result",result);
        System.out.println(result);
    }

    public static void main(String[] args) {
        BankWaterService bankWaterService = new BankWaterService();
        bankWaterService.count();
    }
}
